import { DOMAIN_NAME } from "../../api/config";
import { get } from "../../api/request";

// index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    background: [],
    carouselData: [],
    current: 0,
    currentIndex: 0, // 当前选中的索引
    timeList: [],
    notices: [],
    currentQAIndex: 0,
    qaList: [
      { question: "高考填志愿是按分数还是按名次？" },
      { question: "高考填报志愿早晚有什么区别？" },
      { question: "高考学校录取规则是什么？" },
      { question: "高考填报志愿早晚有区别吗？" },
      { question: "高考志愿填报技巧有哪些？" }
    ],
    firstRowDirection: '',
    secondRowDirection: '',
    lastFirstScrollLeft: 0,
    lastSecondScrollLeft: 0,
    contentType: 'news', // 'video' 或 'news'
    videoList: [],
    newsList: [],
    timeScheduleList: [],
    page: 1,
    pageSize: 4
  },

  // 预约按钮点击事件
  onGridItemClick(e) {
    const index = e.currentTarget.dataset.index;
    const userInfo = wx.getStorageSync('userInfo');

    if (index == 0) { // 预约按钮
      if (userInfo.auth) {
        // 检查用户信息是否完整
        get('/user/my_info').then(res => {
          if (res && res.code === 200 && res.data) {
            const userData = res.data;
            // 检查必要信息是否完整
            const isInfoComplete = this.checkUserInfoComplete(userData);

            if (isInfoComplete) {
              // 信息完整，直接跳转
              wx.navigateTo({
                url: '/pages/appointment/appointment'
              });
            } else {
              // 信息不完整，显示提示弹窗
              wx.showModal({
                title: '提示',
                content: '请先完善个人信息，以便我们更好地为您服务',
                confirmText: '去完善',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    // 用户点击确定，跳转到信息完善页面
                    wx.navigateTo({
                      url: '/pages/student-info/student-info'
                    });
                  }
                  // 用户点击取消，不做任何操作
                }
              });
            }
          }
        });
      } else {
        // 未登录，显示登录弹窗
        this.selectComponent('#loginPopup').showPopup();
      }
    } else if (index == 1) {
      // 志愿表按钮
      if (userInfo.auth) {
        wx.switchTab({
          url: '/pages/tianbao/tianbao'
        });
      } else {
        this.selectComponent('#loginPopup').showPopup();
      }
    }
  },

  // 检查用户信息完整性
  checkUserInfoComplete(userData) {
    // 检查必要信息是否都已填写
    const requiredFields = {
      'real_name': '姓名',
      'sex': '性别',
      'college_score': '高考成绩',
      'place': '位次',
      'contact_number': '联系电话',
      'parent_phone': '家长电话',
      'political': '政审状态',
      'guardian': '监护人情况',
      'f_job': '父亲职业',
      'm_job': '母亲职业',
      'pp_work': '工作认知',
      'idp': '个人发展计划',
      'inland': '地区倾向',
      'tt_specialize': '专业倾向',
      'fill_style': '填报风格'
    };

    // 检查每个必填字段
    for (const [field, label] of Object.entries(requiredFields)) {
      if (userData[field] === undefined || userData[field] === null || userData[field] === '') {
        console.log(`缺少${label}信息`);
        return false;
      }
    }

    return true;
  },

  onSwiperChange(e) {
    this.setData({
      current: e.detail.current
    })
  },

  onLayoutItemClick(e) {
    const id = e.currentTarget.dataset.id;
    if (id === '4') {
      const currentType = this.data.contentType;
      wx.navigateTo({
        url: `/pages/videoDetail/videoDetail?type=${currentType}`
      });
    }
  },

  switchTab(e) {
    const index = Number(e.currentTarget.dataset.index);
    this.setData({
      currentIndex: index
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.type) {
      this.setData({
        contentType: options.type
      });
    }

    // 注册登录组件到全局认证管理器
    const app = getApp();
    if (app && app.globalData.authManager) {
      setTimeout(() => {
        const loginComponent = this.selectComponent('#loginPopup');
        if (loginComponent) {
          app.globalData.authManager.setLoginPopup(loginComponent);
        }
      }, 300); // 稍微延迟以确保组件已完全加载
    }
  },

  checkCurrentPhase: function () {
    let activeIndex = 0;
    if (this.data.timeScheduleList && this.data.timeScheduleList.length > 0) {
      activeIndex = 0;
    } else {
      const currentDate = new Date();
      const dates = [
        new Date('2025-06-07'),  // 高考日程
        new Date('2025-06-25'),  // 高考查分
        new Date('2025-07-05'),  // 志愿填报
        new Date('2025-07-15')   // 录取查询
      ];

      if (currentDate < dates[0]) {
        activeIndex = 0;
      } else if (currentDate < dates[1]) {
        activeIndex = 1;
      } else if (currentDate < dates[2]) {
        activeIndex = 2;
      } else {
        activeIndex = 3;
      }
    }

    this.setData({
      currentIndex: activeIndex
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkCurrentPhase();
    this.getRequest();
    // 如果用户信息不存在，则延迟3秒后获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    setTimeout(() => {
      this.useUserInfo();
      // 用户信息已存在，根据info字段设置contentType
      if (userInfo.info === true) {
        this.setData({
          contentType: 'video'
        });
      } else {
        this.setData({
          contentType: 'news'
        });
      }
    }, 2500);

    // 加载内容数据
    this.loadContentData();
  },

  loadContentData: function () {
    if (this.data.contentType === 'video') {
      this.getVideoList();
    } else {
      this.getNewsList();
    }
  },

  /**
   * 获取视频列表
   */
  getVideoList: function () {
    get(`/index/article?types=2&page=${this.data.page}&pageSize=${this.data.pageSize}`).then(res => {
      if (res.code === 200) {
        // 处理图片URL
        const list = res.data.list.map(item => {
          return {
            ...item,
            cover: DOMAIN_NAME + '/file/' + item.cover,
            videoUrl: item.content,
            duration: this.formatDuration(item.duration || 600) // 默认10分钟
          }
        });
        this.setData({
          videoList: list
        });
      }
    });
  },

  /**
   * 获取新闻列表
   */
  getNewsList: function () {
    get(`/index/article?types=1&page=${this.data.page}&pageSize=${this.data.pageSize}`).then(res => {
      if (res.code === 200) {
        // 处理图片URL和类型
        const list = res.data.list.map(item => {
          return {
            ...item,
            date: item.created_at.split(' ')[0],
            type: this.getArticleType(item.id)
          }
        });
        this.setData({
          newsList: list
        });
      }
    });
  },

  // 根据文章ID生成类型
  getArticleType: function (id) {
    const types = ["政策解读", "系统更新", "招生计划", "填报指南", "专业解析"];
    const index = id % types.length;
    return types[index];
  },

  // 格式化时长
  formatDuration: function (seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
  },

  /**
   * 请求数据 ${请求数据}
   */
  getRequest: function () {
    // 轮播图
    get(`/index/carousel?position=${0}&limit=${0}`).then(res => {
      if (res.code === 200) {
        const { data } = res;
        // console.log('/index/carousel', data);
        // 将数组中的每个图片对象的URL拼接成完整路径
        const backgrounds = data.map(item => DOMAIN_NAME + '/file/' + item.img);
        this.setData({
          background: backgrounds,
          carouselData: data
        })
      }
    });
    //公告
    get(`/index/notice?position=${0}&limit=${0}`).then(res => {
      if (res.code === 200) {
        const { data } = res;
        // 将后端返回的公告数据映射到notices数组
        const notices = data.map(item => ({
          content: item.content,
          date: item.created_at.split(' ')[0] // 只保留年月日部分
        }));
        this.setData({
          notices
        });
      }
    });

    // 获取所有高考时间表数据
    Promise.all([
      get(`/index/time_schedule?types=${1}`), // 高考日程
      get(`/index/time_schedule?types=${0}`)  // 其他时间表
    ]).then(([resExam, resOther]) => {
      let allSchedules = [];

      // 添加高考日程（放在最前面）
      if (resExam.code === 200 && resExam.data && resExam.data.length > 0) {
        console.log('高考时间', resExam.data);
        allSchedules = [...resExam.data];
      }

      // 添加其他时间表
      if (resOther.code === 200 && resOther.data) {
        console.log('其他时间表', resOther.data);
        allSchedules = [...allSchedules, ...resOther.data];
      }

      // 更新时间表数据
      this.setData({
        timeScheduleList: allSchedules
      }, () => {
        // 数据加载完成后，检查当前应该显示哪个阶段
        this.checkCurrentPhase();
      });
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 小程序分享
    return {
      title: '高考志愿填报助手',
      path: '/pages/index/index'
    };
  },
  onFirstRowScroll(e) {
    const currentScrollLeft = e.detail.scrollLeft;
    const direction = currentScrollLeft > this.data.lastFirstScrollLeft ? '' : 'reverse';

    this.setData({
      firstRowDirection: direction,
      lastFirstScrollLeft: currentScrollLeft
    });
  },

  onSecondRowScroll(e) {
    const currentScrollLeft = e.detail.scrollLeft;
    const direction = currentScrollLeft > this.data.lastSecondScrollLeft ? '' : 'reverse';

    this.setData({
      secondRowDirection: direction,
      lastSecondScrollLeft: currentScrollLeft
    });
  },

  useUserInfo: function () {
    get('/user/my').then(res => {
      const { data } = res;
      console.log('用户信息', data);
      // wx.setStorageSync('userInfo', data);

      // 根据用户信息中的info字段设置contentType
      if (data && data.info === true) {
        this.setData({
          contentType: 'video'
        });
      } else {
        this.setData({
          contentType: 'news'
        });
      }

      // 加载对应内容数据
      this.loadContentData();
    });

  }
})